package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Category2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    private CategoryDao categoryDao;
    // 相当于baseMapper

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO 1、先检查当前删除的菜单，是否被别的地方应用

        //直接删除
        baseMapper.deleteBatchIds(asList);
        //若使用逻辑删除

    }

    // [2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        findParentPath(catelogId,paths);
//        List<Long> parentPath=findParentPath(catelogId,paths);
        Collections.reverse(paths);

        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    //使用Cache每次更新数据后删除缓存
//    @CacheEvict(value = {"category"},key = "'getLevel1Categorys'")
    //删除多个缓存,下面两种方法
    @CacheEvict(value = {"category"},allEntries = true)
//    @Caching(evict = {
//            @CacheEvict(value = {"category"},key = "'getLevel1Categorys'"),
//            @CacheEvict(value = {"category"},key = "'getCategoryJson'")})
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //查出所有一级分类
    @Cacheable(value = {"category"},key = "#root.method.name")
    public List<CategoryEntity> getLevel1Categorys() {
//        long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
//        System.out.println("消耗时间："+(System.currentTimeMillis()-l));
        return categoryEntities;
    }

    //版本七，使用SpringCache
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    public Map<String, List<Category2Vo>> getCategoryJson(){
        //0.将数据库的数据一次性全部查出来
        List<CategoryEntity> allList = baseMapper.selectList(null);

        //1.查出所有一级分类l1
        List<CategoryEntity> l1 = getParent_cid(allList, 0L);
        List<CategoryEntity> cid = getParent_cid(allList, 250L);
        //2.封装数据
        Map<String, List<Category2Vo>> collect = l1.stream().collect(Collectors.toMap(key -> key.getCatId().toString(), val -> {
            List<Category2Vo> level23 = null;
            //2.1查询每个一级分类的二级分类l2
            List<CategoryEntity> cid1 = getParent_cid(allList, 250L);
            List<CategoryEntity> l2 = getParent_cid(allList, val.getCatId());
            if (l2 != null) {
                level23 = l2.stream().map(item -> {
                    Category2Vo category2Vo = new Category2Vo(val.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //2.2找当前二级分类的三级分类l3
                    List<CategoryEntity> l3 = getParent_cid(allList, item.getCatId());
                    if (l3 != null) {
                        //2.3把找到的三级分类封装成指定的格式，即Category3Vo
                        List<Category2Vo.Category3Vo> collectL3 = l3.stream().map(item3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        category2Vo.setCatalog3List(collectL3);
                    }
                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return level23;
        }));
        return collect;
    }
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> allList,Long parent_cid) {
        List<CategoryEntity> collect=new LinkedList<>();
        for (CategoryEntity categoryEntity : allList) {
            long pCid=categoryEntity.getParentCid();
            if (pCid==parent_cid){
                collect.add(categoryEntity);
            }
        }
        return collect;
    }

    //版本六：使用Redisson
    /**
     * 前面所有版本都存在问题：
     * 缓存中的数据如何和数据库保存一致？
     * 缓存数据一致性
     * 1）、双写模式
     * 2）、失效模式
     * @return
     */
    public Map<String, List<Category2Vo>> getCategoryJson6() {
        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（加随机值）：解决缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //先从redis缓存中取数据
        String categoryJson = ops.get("categoryJson");
        Map<String, List<Category2Vo>> result=null;
        //若redis缓存中没数据，再从数据库中取
        if (StringUtils.isEmpty(categoryJson)){
            result = getCatalogJsonFromDbWithRedissonLock();
        }else {
            //字符串转为对象
            System.out.println("....到缓存中读取..............");
            result = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Category2Vo>>>() {});
        }

        return result;
    }
    public Map<String, List<Category2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        //锁的名字，锁的粒度，越细越快
        RLock lock = redisson.getLock("CatelogJson-lock");
        lock.lock();

        System.out.println("获取分布式锁成功...");
        Map<String, List<Category2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDB();
        } finally {
            lock.unlock();
        }

        return dataFromDb;
    }

    //版本五：分布式锁
    public Map<String, List<Category2Vo>> getCategoryJson5() {
        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（加随机值）：解决缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //先从redis缓存中取数据
        String categoryJson = ops.get("categoryJson");
        Map<String, List<Category2Vo>> result=null;
        //若redis缓存中没数据，再从数据库中取
        if (StringUtils.isEmpty(categoryJson)){
            result = getCatalogJsonFromDbWithRedisLock();
        }else {
            //字符串转为对象
            System.out.println("....到缓存中读取..............");
            result = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Category2Vo>>>() {});
        }

        return result;
    }
    public Map<String, List<Category2Vo>> getCatalogJsonFromDbWithRedisLock() {
        //1、占分布式锁。去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3000, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功...");
            //加锁成功... 执行业务
            //2、设置过期时间，必须和加锁是同步的，原子的
            //redisTemplate.expire("lock",30,TimeUnit.SECONDS);
            Map<String, List<Category2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDB();
            } finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class)
                        , Arrays.asList("lock"), uuid);
            }
            //获取值对比+对比成功删除=原子操作  lua脚本解锁
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)){
//                //删除我自己的锁
//                redisTemplate.delete("lock");//删除锁
//            }
            return dataFromDb;
        } else {
            //加锁失败...重试。synchronized ()
            //休眠100ms重试
            System.out.println("获取分布式锁失败...等待重试");
            try {
                Thread.sleep(200);
            } catch (Exception e) {

            }
            return getCatalogJsonFromDbWithRedisLock();//自旋的方式
        }
    }
    private Map<String, List<Category2Vo>> getDataFromDB() {
        //得到锁之后，我们应该再去缓存中确定一次，如果没有才继续查询
        String categoryJson = redisTemplate.opsForValue().get("categoryJson");
        if (!StringUtils.isEmpty(categoryJson)) {
            //缓存不为null，直接返回
            Map<String, List<Category2Vo>> result = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Category2Vo>>>() {
            });
            return result;
        }

        System.out.println("....数据库中查询........");
        //0.将数据库的数据一次性全部查出来
        List<CategoryEntity> allList = baseMapper.selectList(null);

        //1.查出所有一级分类l1
        List<CategoryEntity> l1 = getParent_cid(allList, 0L);
        //2.封装数据
        Map<String, List<Category2Vo>> collect = l1.stream().collect(Collectors.toMap(key -> key.getCatId().toString(), val -> {
            List<Category2Vo> level23 = null;
            //2.1查询每个一级分类的二级分类l2
            List<CategoryEntity> l2 = getParent_cid(allList, val.getCatId());
            if (l2 != null) {
                level23 = l2.stream().map(item -> {
                    Category2Vo category2Vo = new Category2Vo(val.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //2.2找当前二级分类的三级分类l3
                    List<CategoryEntity> l3 = getParent_cid(allList, item.getCatId());
                    if (l3 != null) {
                        //2.3把找到的三级分类封装成指定的格式，即Category3Vo
                        List<Category2Vo.Category3Vo> collectL3 = l3.stream().map(item3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        category2Vo.setCatalog3List(collectL3);
                    }
                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return level23;
        }));
        //对象封装为json字符串，再放入缓存中

        String s = JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("categoryJson", s, 1, TimeUnit.DAYS);
        return collect;
    }

    //版本四：本地锁
    public Map<String, List<Category2Vo>> getCategoryJson4() {
        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（加随机值）：解决缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //先从redis缓存中取数据
        String categoryJson = ops.get("categoryJson");
        Map<String, List<Category2Vo>> result=null;
        //若redis缓存中没数据，再从数据库中取
        if (StringUtils.isEmpty(categoryJson)){
            result = getCatalogJsonFromDbWithLocalLock();
        }else {
            //字符串转为对象
            System.out.println("....到缓存中读取..............");
            result = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Category2Vo>>>() {});
        }

        return result;
    }
    public Map<String, List<Category2Vo>> getCatalogJsonFromDbWithLocalLock() {
        synchronized (this) {
            //得到锁之后，我们应该再去缓存中确定一次，如果没有才继续查询
            return getDataFromDB();
        }
    }

    //版本三：使用缓存，Redis
    public Map<String, List<Category2Vo>> getCategoryJson3() {
        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（加随机值）：解决缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        //先从redis缓存中取数据
        String categoryJson = ops.get("categoryJson");
        Map<String, List<Category2Vo>> result=null;
        //若redis缓存中没数据，再从数据库中取
        if (StringUtils.isEmpty(categoryJson)){
            result = getCategoryJsonFromDB3();
//            //对象封装为json字符串，再放入缓存中
//            String s = JSON.toJSONString(result);
//            ops.set("categoryJson",s,1, TimeUnit.DAYS);
        }else {
            //字符串转为对象
            System.out.println("....到缓存中读取..............");
            result = JSON.parseObject(categoryJson, new TypeReference<Map<String, List<Category2Vo>>>() {});
        }

        return result;
    }
    public Map<String, List<Category2Vo>> getCategoryJsonFromDB3() {
        System.out.println("....数据库中查询........");
        //0.将数据库的数据一次性全部查出来
        List<CategoryEntity> allList = baseMapper.selectList(null);

        //1.查出所有一级分类l1
        List<CategoryEntity> l1 = getParent_cid(allList,0L);
        //2.封装数据
        Map<String, List<Category2Vo>> collect = l1.stream().collect(Collectors.toMap(key -> key.getCatId().toString(), val -> {
            List<Category2Vo> level23 = null;
            //2.1查询每个一级分类的二级分类l2
            List<CategoryEntity> l2 = getParent_cid(allList,val.getCatId());
            if (l2 != null) {
                level23 = l2.stream().map(item -> {
                    Category2Vo category2Vo = new Category2Vo(val.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //2.2找当前二级分类的三级分类l3
                    List<CategoryEntity> l3 = getParent_cid(allList,item.getCatId());
                    if (l3!=null){
                        //2.3把找到的三级分类封装成指定的格式，即Category3Vo
                        List<Category2Vo.Category3Vo> collectL3 = l3.stream().map(item3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        category2Vo.setCatalog3List(collectL3);
                    }
                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return level23;
        }));
        //对象封装为json字符串，再放入缓存中
        String s = JSON.toJSONString(collect);
        redisTemplate.opsForValue().set("categoryJson",s,1, TimeUnit.DAYS);
        return collect;
    }

    //版本二：优化版本一，一次查出所有数据，再以后需要的时候做数据过滤筛选出需要的数据
    //查询所有一级分类对应的2,3级字分类
    public Map<String, List<Category2Vo>> getCategoryJson2() {
        //0.将数据库的数据一次性全部查出来
        List<CategoryEntity> allList = baseMapper.selectList(null);

        //1.查出所有一级分类l1
        List<CategoryEntity> l1 = getParent_cid(allList,0L);
        //2.封装数据
        Map<String, List<Category2Vo>> collect = l1.stream().collect(Collectors.toMap(key -> key.getCatId().toString(), val -> {
            List<Category2Vo> level23 = null;
            //2.1查询每个一级分类的二级分类l2
            List<CategoryEntity> l2 = getParent_cid(allList,val.getCatId());
            if (l2 != null) {
                level23 = l2.stream().map(item -> {
                    Category2Vo category2Vo = new Category2Vo(val.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //2.2找当前二级分类的三级分类l3
                    List<CategoryEntity> l3 = getParent_cid(allList,item.getCatId());
                    if (l3!=null){
                        //2.3把找到的三级分类封装成指定的格式，即Category3Vo
                        List<Category2Vo.Category3Vo> collectL3 = l3.stream().map(item3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        category2Vo.setCatalog3List(collectL3);
                    }
                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return level23;
        }));
        return collect;
    }


    //版本一：性能差，循环查数据库
//    //查询所有一级分类对应的2,3级字分类
    public Map<String, List<Category2Vo>> getCategoryJson1() {
        //1.查出所有一级分类l1
        List<CategoryEntity> l1 = getLevel1Categorys();
        //2.封装数据
        Map<String, List<Category2Vo>> collect = l1.stream().collect(Collectors.toMap(key -> key.getCatId().toString(), val -> {
            List<Category2Vo> level23 = null;
            //2.1查询每个一级分类的二级分类l2
            List<CategoryEntity> l2 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", val.getCatId()));
            if (l2 != null) {
                level23 = l2.stream().map(item -> {
                    Category2Vo category2Vo = new Category2Vo(val.getCatId().toString(), null, item.getCatId().toString(), item.getName());
                    //2.2找当前二级分类的三级分类l3
                    List<CategoryEntity> l3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", item.getCatId()));
                    if (l3!=null){
                        //2.3把找到的三级分类封装成指定的格式，即Category3Vo
                        List<Category2Vo.Category3Vo> collectL3 = l3.stream().map(item3 -> {
                            Category2Vo.Category3Vo category3Vo = new Category2Vo.Category3Vo(item.getCatId().toString(), item3.getCatId().toString(), item3.getName());
                            return category3Vo;
                        }).collect(Collectors.toList());
                        category2Vo.setCatalog3List(collectL3);
                    }
                    return category2Vo;
                }).collect(Collectors.toList());
            }
            return level23;
        }));
        return collect;
    }

    //递归收集节点id
    private void findParentPath(Long catelogId,List<Long> paths){
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
    }

    // 查出所有分类以及子分类，以树形结构组装起来
    public List<CategoryEntity> listWithTree() {
        // 1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 2、组装成父子的树形结构
        // 2.1、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == 0;
        }).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    // 递归找到所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children=all.stream().filter((categoryEntity)->{
            return categoryEntity.getParentCid().equals(root.getCatId());
        }).map((menu)->{
            // 1、找到子菜单
            menu.setChildren(getChildrens(menu,all));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

}